import { Component, _decorator, sys } from 'cc';
import { LOG } from '../ConsoleLogCtrl';

const { ccclass, property } = _decorator;

@ccclass('MainView')
export class MainView extends Component {
    start(): void {
        // 在游戏加载完成后，通知父页面iframe已准备就绪
        LOG.log('Main页面加载了');
        this.notifyParentReady();
    }

    private notifyParentReady() {
        // 只在浏览器环境下发送ready消息
        if (sys.isBrowser) {
            LOG.log('通知父页面Cocos已准备就绪');
            const readyMessage = {
                type: 'ready',
                source: 'cocos',
                timestamp: Date.now(),
            };
            // 直接通过postMessage发送到父窗口
            if (window.parent && window.parent !== window) {
                window.parent.postMessage(readyMessage, '*');
                LOG.log('已通过postMessage发送ready消息到父窗口');
            }
        } else {
            LOG.log('非浏览器环境，跳过ready消息发送');
        }
    }
}
